package com.ny.dao.impl;

import com.ny.dao.ManagerDao;
import com.ny.entity.Manager;
import com.ny.until.DbUtil;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class ManagerDaoImpl implements ManagerDao {
    private final DbUtil dbUtil = new DbUtil();

    @Override
    public Manager selectManager(String name, String password) throws SQLException {
        String sql = "SELECT * FROM managers WHERE name = ? AND password = ?";
        try (Connection conn = dbUtil.getCon();
             PreparedStatement ps = conn.prepareStatement(sql)) {

            ps.setString(1, name);
            ps.setString(2, password);

            try (ResultSet rs = ps.executeQuery()) {
                if (rs.next()) {
                    return createManagerFromResultSet(rs);
                }
            }
        }
        return null;
    }

    @Override
    public Manager getManagerById(int managerId) throws SQLException {
        String sql = "SELECT * FROM managers WHERE manager_id = ?";
        try (Connection conn = dbUtil.getCon();
             PreparedStatement ps = conn.prepareStatement(sql)) {

            ps.setInt(1, managerId);

            try (ResultSet rs = ps.executeQuery()) {
                if (rs.next()) {
                    return createManagerFromResultSet(rs);
                }
            }
        }
        return null;
    }

    @Override
    public int updateManager(Manager manager) throws SQLException {
        String sql = "UPDATE managers SET name = ?, password = ?, phone = ?, WHERE manager_id = ?";
        try (Connection conn = dbUtil.getCon();
             PreparedStatement ps = conn.prepareStatement(sql)) {

            ps.setString(1, manager.getUsername());
            ps.setString(2, manager.getUserpassword());
            ps.setString(3, manager.getPhone());
            ps.setInt(4, manager.getManagerId());

            return ps.executeUpdate();
        }
    }

    private Manager createManagerFromResultSet(ResultSet rs) throws SQLException {
        Manager manager = new Manager();
        manager.setManagerId(rs.getInt("manager_id"));
        manager.setUsername(rs.getString("name"));
        manager.setUserpassword(rs.getString("password"));
        manager.setPhone(rs.getString("phone"));
        return manager;
    }
}